package cn.gson.oasys.config;

import cn.gson.oasys.pojo.AoaUser;
import cn.gson.oasys.service.AoaUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;

/**
 * Created by ASUS on 2020/12/2.
 */
//自定义Realm
public class UserRealm extends AuthorizingRealm{    //将这个AuthorizingRealm改成

    @Resource
    private AoaUserService aoaUserService;

    //授权 大操作
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》授权的doGetAuthorizationInfo");

        //给资源授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加资源授权字符串
        info.addStringPermission("aoaUser:index");
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了=》认证的doGetAuthorizationInfo");

        UsernamePasswordToken userToken=(UsernamePasswordToken) token;

        //密码需要强转
        String password = new String(userToken.getPassword());
        //连接真实的数据库
        AoaUser aoaUser= aoaUserService.getByNameAndPassword(userToken.getUsername(),password);

        //判断是否验证成功
        if(aoaUser==null){
            return null;   //Controller会Catch:UnknownAccountException
        }

        //密码认证Shiro做   可以获取认证加密
        //可以加密： MD5：827ccb0eea8a706c4c34a16891f84e7b  MD5盐值加密：827ccb0eea8a706c4c34a16891f84e7busername
        return new SimpleAuthenticationInfo(aoaUser,aoaUser.getPassword(),"");
    }
}
